using System;   
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

using Alicanto.Helpers;
using Alicanto.Lexing;

namespace Alicanto.Compilation.Code.SpecialNames
{
    internal class ReturnToMe : ICodeGenerator
    {
        public Expression Code { get; private set; }
        private static int i = 0;

        public IEnumerable<ParseInstruction> Generate(TokenSequence tokens, Scope scope)
        {
            i++;
            EnterScope enter = new EnterScope();
            yield return enter;

            // Define return label
            enter.Scope.RegisterLabel("return", Expression.Label(typeof(object), "r" + i));

            // Parenthesis closure can be expected
            int closed = 0;
            while (tokens.Peek() == Token.BracketClose)
            {
                tokens.Pop();
                closed++;
            }

            ParseBlock right = new ParseBlock();
            yield return right;

            yield return new LeaveScope();

            List<Expression> statements = new List<Expression>();
            statements.Add(right.Block);
            statements.Add(
                Expression.Label(
                    enter.Scope.ResolveLabel("return"),
                    Expression.Default(typeof(object))
                )
            );

            this.Code = Expression.Block(
                statements
            );

            while (closed > 0)
            {
                closed--;
                tokens.Insert(Token.BracketOpen);
            }
        }
    }
}
